/**
 * Created by jiadx on 2015/11/13.
 */
define(['ionic'], function() {
    angular.module('SalesShipments.controllers', [])

    .controller('DivisionCtrl', ['$scope', '$state', 'SalesShipmentsService',
            function($scope, $state, SalesShipmentsService) {
                $scope.data = {
                    division: []
                };
                SalesShipmentsService.queryDivision().then(function(data) {
                    $scope.data.division = data;
                });
                $scope.addDivision = function(division) {
                    SalesShipmentsService.selectDivision(division).then(function() {
                        $state.go('contact');
                    }, function() {
                        u9.tipsBottom("提取事业部信息失败！");
                    });

                }
            }
        ])
        .controller('ContactCtrl', ['$scope', '$state', 'SalesShipmentsService',
            function($scope, $state, SalesShipmentsService) {
                $scope.data = {
                    contacts: [],
                    search: '',
                    quickCambers: [],
                    activeCamber: 'Z',
                    page: 1,
                    keywords: '',
                    scrolled: false,
                    loadOver: false
                };

                function stratSearch() {
                    $scope.data.page = 1;
                    SalesShipmentsService.queryContacts($scope.data.page, $scope.data.keywords)
                        .then(function(data) {
                            $scope.data.contacts = data.contact;
                            if (data.flag) {
                                $scope.data.page += 1;
                                $scope.data.scrolled = true;
                                $scope.data.loadOver = false;
                            } else {
                                $scope.data.scrolled = false;
                                $scope.data.loadOver = true;
                            }
                        }, function() {
                            $scope.data.scrolled = false;
                            $scope.data.loadOver = true;
                        });
                }

                $scope.loadMore = function() {
                    reuestServer();
                };

                function reuestServer() {
                    SalesShipmentsService.queryContacts($scope.data.page, $scope.data.keywords)
                        .then(function(data) {
                            $scope.data.contacts = data.contact;
                            if (data.flag) {
                                $scope.data.page += 1;
                                $scope.data.scrolled = true;
                                $scope.data.loadOver = false;
                            } else {
                                $scope.data.scrolled = false;
                                $scope.data.loadOver = true;
                            }
                            $scope.$broadcast('scroll.infiniteScrollComplete');
                        }, function() {
                            $scope.data.scrolled = false;
                            $scope.data.loadOver = true;
                            $scope.$broadcast('scroll.infiniteScrollComplete');
                        });
                }

                $scope.addContacts = function(item) {
                    SalesShipmentsService.selectContacts(item).then(function() {
                        $state.go('merchandise');
                    }, function() {
                        alert("提取客户信息失败！");
                    });
                };

                $scope.$watch('data.search', function(search) {
                    $scope.data.keywords = search;
                    stratSearch();
                });

                $scope.goDivision = function() {
                    $state.go('division');
                };
            }
        ])
        .controller('MerchandiseCtrl', ['$scope', '$state', 'SalesShipmentsService', 'UtilService',
            function($scope, $state, SalesShipmentsService, UtilService) {
                $scope.data = {
                    merchandise: [],
                    search: '',
                    NoMsg: true,
                    scrolled: true,
                    loadOver: false,
                    displayData: 8,
                    page: 1,
                    merNum: 0
                };
                //请求服务器
                $scope.doRefresh = function() {
                    $scope.data.merchandise = [];
                    SalesShipmentsService.queryMerchandise(1, SalesShipmentsService.getContact().id, true)
                        .then(function(data) {
                            $scope.data.merchandise = data.merchandise;
                            $scope.data.page = 1;
                            $scope.data.scrolled = true;
                            $scope.data.loadOver = false;
                            $scope.$broadcast('scroll.refreshComplete');
                        }, function() {
                            $scope.$broadcast('scroll.refreshComplete');
                        });
                };

                $scope.loadMore = function() {
                    SalesShipmentsService.queryMerchandise($scope.data.page, SalesShipmentsService.getContact().id)
                        .then(function(data) {
                            $scope.data.merchandise = data.merchandise;
                            if (data.flag) {
                                $scope.data.page += 1;
                            } else {
                                $scope.data.scrolled = false;
                                $scope.data.loadOver = true;
                            }

                            if (Object.getOwnPropertyNames(SalesShipmentsService.getMerchandise()).length > 0) {
                                $scope.data.merNum = Object.getOwnPropertyNames(SalesShipmentsService.getMerchandise()).length;
                            }
                            $scope.$broadcast('scroll.infiniteScrollComplete');
                        }, function() {
                            $scope.data.scrolled = false;
                            $scope.data.loadOver = true;
                            $scope.$broadcast('scroll.infiniteScrollComplete');
                        });
                };

                $scope.addMerchandise = function(checked, merchandise) {
                    var t = {
                        merchandiseId: merchandise.MerchandiseId,
                        name: merchandise.Name,
                        spec: merchandise.Spec,
                        symbols: merchandise.CurrencySymbols,
                        price: merchandise.Price,
                        unit: merchandise.Unit,
                        num: 1,
                        subtotal: merchandise.Price,
                        giveawayChecked: false,
                        picture: merchandise.Picture
                    };

                    SalesShipmentsService.addMerchandise(checked, t).then(function(flag) {
                        if (flag == true) {
                            $scope.data.merNum += 1;
                        } else {
                            $scope.data.merNum -= 1;
                        }
                    });
                };

                $scope.$watch('data.search', function(search) {
                    if (search.length > 0) {
                        SalesShipmentsService.getMerchandiseByValue(search, SalesShipmentsService.getContact().id)
                            .then(function(data) {
                                $scope.data.merchandise = data;
                            });
                    }
                });

                $scope.goOrders = function() {
                    $state.go('order');
                };

            }
        ])
        .controller('OrderCtrl', ['$scope', '$state', 'SalesShipmentsService',
            function($scope, $state, SalesShipmentsService) {
                $scope.data = {
                    orders: SalesShipmentsService.getMerchandise(),
                    totalMoney: 0,
                    actualCost: 0,
                    returnCost: 0,
                    contact: SalesShipmentsService.getContact(),
                    divisions: {
                        userName: u9.getLoginData().UserCode,
                        division: SalesShipmentsService.getDivision()
                    },
                    bankNo: "",
                    count: 0,
                    scale: SalesShipmentsService.getContact().Gather,
                    logistics: '',
                    mark: ''
                };
                var curYear, curMonth, curDay;
                var curDate = new Date();
                curYear = curDate.getFullYear().toString();
                curMonth = (curDate.getMonth() + 1).toString();
                curDay = curDate.getDate().toString();

                if (curMonth.length < 2) {
                    curMonth = "0" + curMonth;
                }
                if (curDay.length < 2) {
                    curDay = "0" + curDay;
                }
                $scope.data.receiptDate = curYear + '-' + curMonth + '-' + curDay;
                angular.forEach($scope.data.orders, function(order) {
                    $scope.data.totalMoney += order.subtotal;
                    $scope.data.count += 1;
                });
                //初始化返现金额
                moneySum();

                /*解决input输入的问题*/
                if (window.parent.cordova) {
                    $scope.hideKeyboard = function() {
                        window.focus();
                        window.parent.Keyboard.disableScroll(true);
                        window.parent.close();
                    };
                }

                $scope.selectDate = function() {
                    var curDate = new Date();

                    if ($scope.data.receiptDate) {
                        var ym = $scope.data.receiptDate.split('-');
                        var year = ym[0];
                        var month = ym[1] - 1;
                        var day = ym[2];
                        curDate = new Date(year, month, day);
                    }
                    var options = {
                        date: curDate,
                        mode: 'date',
                        doneButtonLabel: '确定',
                        cancelButtonLabel: "取消"
                    };
                    u9.plugins.datePicker.show(options, function(date) {
                        if (date == 'Invalid Date' || date == 'Nan-Nan') {
                            return;
                        }

                        curYear = date.getFullYear().toString();
                        curMonth = (date.getMonth() + 1).toString();
                        curDay = date.getDate().toString();

                        if (curMonth.length < 2) {
                            curMonth = "0" + curMonth;
                        }
                        if (curDay.length < 2) {
                            curDay = "0" + curDay;
                        }
                        $scope.data.receiptDate = curYear + '-' + curMonth + '-' + curDay;

                        $scope.$apply();
                    });
                };

                $scope.raiseOrReduce = function(obj, flag) {
                    if (flag == 'reduce') {
                        if (obj.num > 1) {
                            obj.num -= 1;
                        }
                    }
                    if (flag == 'raise') {
                        obj.num += 1;
                    }
                    if (!obj.giveawayChecked) {
                        $scope.data.totalMoney = $scope.data.totalMoney - obj.subtotal + obj.num * obj.price;
                        moneySum();
                    }
                    obj.subtotal = obj.num * obj.price;
                };

                $scope.numChg = function(obj) {
                    var num = obj.num;
                    if (num == undefined) {
                        num = 0;
                    }
                    $scope.data.totalMoney = $scope.data.totalMoney - obj.subtotal + num * obj.price;
                    obj.subtotal = num * obj.price;
                    moneySum();

                };

                $scope.markGiveaway = function(index, flag, obj) {
                    $scope.data.totalMoney -= obj.subtotal;
                    $scope.data.count -= 1;
                    moneySum();
                    obj.giveawayChecked = flag;
                    angular.element(document.querySelector('#giveaway' + index)).addClass('giveawayFlag');

                };
                $scope.markNoGiveaway = function(index, flag, obj) {
                    $scope.data.totalMoney += obj.subtotal;
                    $scope.data.count += 1;
                    moneySum();
                    obj.giveawayChecked = flag;
                    angular.element(document.querySelector('#giveaway' + index)).removeClass('giveawayFlag');
                };

                $scope.trashOrder = function(obj) {
                    if (!obj.giveawayChecked) {
                        $scope.data.totalMoney -= obj.subtotal;
                        $scope.data.count -= 1;
                    }
                    SalesShipmentsService.deleteShoppingCart(obj);
                };

                function moneySum() {
                    $scope.data.actualCost = ($scope.data.totalMoney * $scope.data.scale / 100).toFixed(2);
                    $scope.data.returnCost = (($scope.data.totalMoney * 100 - Number($scope.data.actualCost) * 100) / 100).toFixed(2);
                }

                $scope.checkText = function(value) {
                    if (value) {
                        if (value.toString().length > 20) {
                            $scope.data.bankNo = value.substr(0, 24);
                        } else {
                            $scope.data.bankNo = value.replace(/\s/g, '').replace(/(\d{4})(?=\d)/g, "$1 ");
                        }
                    }
                };
                $scope.resetContact = function() {
                    u9.confirm('确定后,您之前的操作将被重置。', '确定要更换客户吗？').then(function(res) {
                        if (res) {
                            SalesShipmentsService.clearShoppingCart();
                            $state.go('contact');
                        }
                    });
                };

                $scope.buyOrders = function(orders) {

                    var orderList = [];
                    var shipDocList = {
                        OrgID: u9.getLoginData().OrgId,
                        Date: $scope.data.receiptDate,
                        Operater: $scope.data.divisions.userName,
                        Customer: $scope.data.contact.ContactId,
                        Amount: $scope.data.totalMoney,
                        CollectAmount: $scope.data.actualCost,
                        RebateAmount: $scope.data.returnCost,
                        CardNumber: $scope.data.bankNo,
                        Logistics: $scope.data.contact.Logistics,
                        Mark: $scope.data.mark,
                        DocTypeID: $scope.data.divisions.division.DivisionId,
                        Linelist: []
                    };

                    angular.forEach(orders, function(order) {
                        var t;
                        if (!order.giveawayChecked) {
                            t = {
                                ItemID: order.merchandiseId,
                                Qty: order.num,
                                Price: order.price
                            };

                        } else {
                            t = {
                                ItemID: order.merchandiseId,
                                Qty: order.num,
                                Price: 0
                            };
                        }
                        shipDocList.Linelist.push(t);
                    });
                    if (shipDocList.Linelist == 0) {
                        u9.alert("订单列表为空，请选择商品。");
                        return;
                    }
                    // if (shipDocList.CardNumber == "") {
                    //     u9.alert("银行卡号不能为空");
                    //     return;
                    // }
                    // if(!verify(shipDocList.CardNumber)){
                    //     u9.alert("银行卡号不符合要求");
                    //     return;
                    // }

                    orderList.push(shipDocList);
                    SalesShipmentsService.buyOrders(orderList).then(function(flag) {
                        if (flag == true) {
                            u9.alert('下单成功!');
                            SalesShipmentsService.clearShoppingCart();
                            $state.go('contact');
                        } else {
                            u9.alert('下单失败!');
                        }
                    });
                };

                // function verify(value) {
                //     var arr = value.replace(/\s+/g, "").split(/(\d)$/); // ["621228880200000166", "6", ""]
                //     var preTotal = arr[0].split('')
                //         .reverse()
                //         .map(function(x, idx) {
                //             return (idx + 1) % 2 == 0 ? x * 1 : x * 2;
                //         })
                //         .map(function(x) {
                //             return x >= 10 ? x - 9 : x;
                //         })
                //         .reduce(function(x, y) {
                //             return x + y;
                //         });
                //     var total = arr[1] * 1 + preTotal;
                //     return isValid = total % 10 == 0;
                // }
            }
        ]);

});